package xyz.xtt.admin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.xtt.admin.constants.*;
import xyz.xtt.admin.entity.TblAsset;
import xyz.xtt.admin.entity.TblAssetTransaction;
import xyz.xtt.admin.entity.TblUser;
import xyz.xtt.admin.mapper.AssetTransactionMapper;
import xyz.xtt.admin.request.AssetTransactionListRequest;
import xyz.xtt.admin.service.IAssetTransactionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.xtt.admin.vo.AssetTransactionVo;

import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 资产交易记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-03
 */
@Service
public class AssetTransactionServiceImpl extends ServiceImpl<AssetTransactionMapper, TblAssetTransaction> implements IAssetTransactionService {

    @Autowired
    private  AssetTransactionMapper assetTransactionMapper;

    @Override
    public Page<AssetTransactionVo> list(AssetTransactionListRequest assetTransactionListRequest) {
        MPJLambdaWrapper<TblAssetTransaction> query = JoinWrappers.lambda(TblAssetTransaction.class)
                .leftJoin(TblUser.class, "sell", TblUser::getAppUserId, TblAssetTransaction::getSellerUserId)
                .leftJoin(TblUser.class, "buy", TblUser::getAppUserId, TblAssetTransaction::getBuyerUserId)
                .leftJoin(TblAsset.class, TblAsset::getGoodsId, TblAssetTransaction::getGoodsId);

        // 判断开始时间
        if(StringUtils.isNotBlank(assetTransactionListRequest.getStartCreateDatetime())) {
            try {
                Long startDate = parseDate(assetTransactionListRequest.getStartCreateDatetime());
                query.gt(TblAssetTransaction::getDealCreateDatetime , startDate);
            } catch (Exception e) {
                return  null;
            }
        }

        if(StringUtils.isNotBlank(assetTransactionListRequest.getEndCreateDatetime())) {
            try {
                Long endDate = parseDate(assetTransactionListRequest.getEndCreateDatetime());
                query.le(TblAssetTransaction::getDealCreateDatetime , endDate);
            } catch (Exception e) {
                return  null;
            }
        }
        if(StringUtils.isNotBlank(assetTransactionListRequest.getId())) {
            query.eq(TblAssetTransaction::getAssetId, Long.parseLong(assetTransactionListRequest.getId()));
        }

        query.eq(StringUtils.isNotBlank(assetTransactionListRequest.getBuyerUserId()), TblUser::getAppUserId, assetTransactionListRequest.getBuyerUserId())
            .eq(StringUtils.isNotBlank(assetTransactionListRequest.getSellerUserId()),TblUser::getAppUserId, assetTransactionListRequest.getSellerUserId())
            .eq(StringUtils.isNotBlank(assetTransactionListRequest.getSellerUserPhone()),TblUser::getPhone, assetTransactionListRequest.getSellerUserPhone())
            .eq(StringUtils.isNotBlank(assetTransactionListRequest.getBuyerUserPhone()),TblUser::getPhone, assetTransactionListRequest.getBuyerUserPhone())
            .eq(StringUtils.isNotBlank(assetTransactionListRequest.getId()), TblAssetTransaction::getAssetId, assetTransactionListRequest.getId())
            .eq(StringUtils.isNotBlank(assetTransactionListRequest.getGoodsId()), TblAssetTransaction::getGoodsId, assetTransactionListRequest.getGoodsId())
            .eq(assetTransactionListRequest.getDealState()  != null, TblAssetTransaction::getDealState, assetTransactionListRequest.getDealState())
            .selectAll(TblAssetTransaction.class)
            .selectAs("buy", TblUser::getNickname, AssetTransactionVo::getBuyerUserName)
            .selectAs("sell", TblUser::getNickname, AssetTransactionVo::getSellerUserName)
            .selectAs( TblAsset::getFirstType, AssetTransactionVo::getFirstType)
            .selectAs( TblAsset::getSecondType, AssetTransactionVo::getSecondType)
            .select(TblAsset::getAssetName);

        Page<AssetTransactionVo> pageList = assetTransactionMapper.selectJoinPage(
                new Page<>(assetTransactionListRequest.getCurrent(), assetTransactionListRequest.getPageSize()),
                AssetTransactionVo.class,
                query
        );
        List<AssetTransactionVo> records = pageList.getRecords();
        List<AssetTransactionVo> list = records.stream().peek(x -> {
            x.setSellPatternName(SellPatternEnum.queryConvert(x.getSellPattern()).desc());
            x.setDealStateName(DealStateEnum.queryConvert(x.getDealState()).desc());
            x.setUnitName(null == PayUnitEnum.queryConvert(x.getUnit()) ? "" : PayUnitEnum.queryConvert(x.getUnit()).desc());
            x.setPayStateName(DealStateEnum.queryConvert(x.getPayState()).desc());
            x.setClassName(getClassName(x.getFirstType(), x.getSecondType()));
        }).toList();
        pageList.setRecords(list);
        return  pageList;
    }

    private String getClassName(Integer firstType, Integer secondType) {
        // 获取一级分类
        AssetTypeEnum assetTypeEnum = AssetTypeEnum.queryConvert(firstType);
        if (assetTypeEnum == null) {
            return "";
        }
        String className = "";
        switch (assetTypeEnum.code()) {
            case 0:
                GroundTypeEnum groundTypeEnum = GroundTypeEnum.queryConvert(secondType);
                className = String.format("%s/%s",assetTypeEnum.desc(), groundTypeEnum == null? "":groundTypeEnum.desc());
                break;
            case 1:
                CertificateTypeEnum certificateTypeEnum = CertificateTypeEnum.queryConvert(secondType);
                className = String.format("%s/%s", assetTypeEnum.desc(), certificateTypeEnum == null? "" :certificateTypeEnum.desc());
                break;
            default : {
                className =  assetTypeEnum.desc();
                break;
            }
        }
        return className;
    }


    private Long parseDate(String dateString) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(dateString);
        return  date.getTime();
    }

}
